package com.emm.yixun.website.controller.job;

import java.util.Date;
//框架包
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.model.enums.MerchantEnum;
import com.emm.yixun.common.utils.*;
import com.emm.yixun.customer.service.CustomerServiceFacade;
import com.emm.yixun.system.service.pmo.PmoDynamicDataServiceFacade;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.common.enums.ResponseEnums;
import com.emm.yixun.common.model.ActOaLog;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.ProjectPmo;
import com.emm.yixun.common.model.dto.ActOaLogDto;
import com.emm.yixun.common.model.dto.PmoLogDto;
import com.emm.yixun.common.model.dto.ProjectDto;
import com.emm.yixun.common.model.dto.ProjectPmoDto;
import com.emm.yixun.common.model.enums.OperationStatusEnum;
import com.emm.yixun.common.model.pmo.LevelDynamiSalesData;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.customer.service.FollowServiceFacade;
import com.emm.yixun.estate.service.ProjectPmoServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.system.service.ActOaLogServiceFacade;
import com.emm.yixun.system.service.NoticeServiceFacade;
import com.emm.yixun.system.service.NoticeTemporaryServiceFacade;
import com.emm.yixun.system.service.PmoLogServiceFacade;
import com.emm.yixun.website.constant.PmoConfig;
import com.emm.yixun.website.controller.base.BaseController;
//common
//common
//website
//变化的引用

@Controller
@RequestMapping("/job/test/")
public class JobTestController extends BaseController<Customer> {
	
	@Autowired
	private NoticeServiceFacade noticeServiceFacade;
	
	@Autowired
	private FollowServiceFacade followServiceFacade;
	
	@Autowired
	private NoticeTemporaryServiceFacade noticeTemporaryServiceFacade;
	
	@Autowired
	private ActOaLogServiceFacade actOaLogServiceFacade;
	
	@Autowired
	private ProjectServiceFacade projectServiceFacade;

	@Autowired
	private ProjectPmoServiceFacade projectPmoServiceFacade;

	@Autowired
	private PmoConfig pmoConfig;

	@Autowired
	private PmoLogServiceFacade pmoLogServiceFacade;
	@Autowired
	private PmoDynamicDataServiceFacade pmoDynamicDataServiceFacade;
	@Autowired
	private CustomerServiceFacade customerServiceFacade;

	/**
	 * 创建客户维护消息
	 * @param request
	 * @param map
	 */
	@RequestMapping(value="createCusManageNotice")
	public void createCusManageNotice(HttpServletRequest request, ModelMap map) {
		noticeServiceFacade.customerManageNotice();
	}
	
	/**
	 * 创建客户关怀消息
	 * @param request
	 * @param map
	 */
	@RequestMapping(value="createCusCareNotice")
	public void customerManage(HttpServletRequest request, ModelMap map) {
		noticeServiceFacade.customerCareNotice();
	}
	
	/**
	 * 客户关怀当天提醒
	 * @param request
	 * @param map
	 */
	@RequestMapping(value="customerCarePushMsgCurr")
	public void customerCarePushMsgCurr(HttpServletRequest request, ModelMap map) {
		noticeServiceFacade.customerCarePushMsgCurr();
	}
	
	/**
	 * 客户关怀提前提醒
	 * @param request
	 * @param map
	 */
	@RequestMapping(value="customerCarePushMsg")
	public void customerCarePushMsg(HttpServletRequest request, ModelMap map) {
		noticeServiceFacade.customerCarePushMsg();
	}
	
	/**
	 * 创建员工关怀
	 * @param request
	 * @param map
	 */
	@RequestMapping(value="userCareNotice")
	public void userCareNotice(HttpServletRequest request, ModelMap map) {
		noticeServiceFacade.userCareNotice();
	}
	
	/**
	 * 员工关怀
	 * @param request
	 * @param map
	 */
	@RequestMapping(value="userCarePushMsgCurr")
	public void userCarePushMsgCurr(HttpServletRequest request, ModelMap map) {
		noticeServiceFacade.userCarePushMsgCurr();
	}
	
	/**
	 * 跟进记录
	 * @param request
	 * @param map
	 */
	@RequestMapping(value="customerFollowPushMsg")
	public void customerFollowPushMsg(HttpServletRequest request, ModelMap map) {
		followServiceFacade.customerFollowPushMsg();
	}
	
	/**
	 * 推送消息
	 * @param request
	 * @param map
	 */
	@RequestMapping(value="noticeTemporary")
	public void noticeTemporary(HttpServletRequest request, ModelMap map) {
		noticeTemporaryServiceFacade.selectNoticeTemporary();
	}
	
	/**
	 * 逾期未付款
	 * @param request
	 * @param map
	 */
	@RequestMapping(value="customerNoPaymentNotice")
	public void customerNoPaymentNotice(HttpServletRequest request, ModelMap map) {
		noticeServiceFacade.customerNoPaymentNotice();
	}
	
	/**
	 * 逾期未签约
	 * @param request
	 * @param map
	 */
	@RequestMapping(value="customerNoSignedNotice")
	public void customerNoSignedNotice(HttpServletRequest request, ModelMap map) {
		noticeServiceFacade.customerNoSignedNotice();
	}
	
	/**
	 * 推送流程任务至OA
	 * 
	 * @param request
	 * @param map
	 */
	@RequestMapping(value="actTaskSendToOaJob")
	public void actTaskSendToOaJob(HttpServletRequest request, ModelMap map) {
		 logger.info("act task send to oa job start..........");
    	 //生成时间段内需推送的任务集合
		 String startDate = request.getParameter("startDate");
		 String endDate = request.getParameter("endDate");
		 //生成推送任务信息
		 if(StringUtils.isNotEmpty(startDate)
			|| StringUtils.isNotEmpty(endDate)){
			 actOaLogServiceFacade.buildSendTask(startDate, endDate);
		 }
    	 
    	 //推送任务至OA
    	 String url = pmoConfig.getActTaskOaUrl();
    	 ResponseList<ActOaLog> aolListRes  =  actOaLogServiceFacade.findSendtoOaListByDto();
		 if(aolListRes.isSuccess()){
    		 List<ActOaLog> aolList = aolListRes.getEntity();
    		 if(null != aolList && aolList.size() > 0){
    			 for(ActOaLog aol: aolList){
    		    	 String operationStatus = OperationStatusEnum.FAILURE.getNo();
    		    	 String result = "send to oa exception: ";
    		    	 try{
    		    		 result = HttpUtil.doPostByString(url, aol.getReceiveSendMsg(),"UTF-8");
        		    	 if(StringUtils.isNotEmpty(result)){
        		    		 JSONObject object = JSONObject.parseObject(result);
        		    		 String code = object.getString("code");
        		    		 if("200".equals(code)){
        		    			 operationStatus = OperationStatusEnum.SUCCESS.getNo();
        		    		 }
        		    	 }
    		    	 }catch(Exception ex){
    		    		 ex.printStackTrace();
    		    		 result = "send to oa exception: " + ex.getMessage();
    		    		 logger.error("推送任务至OA异常: ", ex);
    		    	 }
    		    	 ActOaLogDto aolDto = new ActOaLogDto();
    		    	 aolDto.setId(aol.getId());
    		    	 aolDto.setOperationStatus(operationStatus);
    		    	 aolDto.setReturnMsg(result);
    		    	 actOaLogServiceFacade.updateByPrimaryKey(aolDto, true);
        		 }
    		 }
    	 }
	}
	
	/**
	 * 推送PMO数据,绿城专属功能
	 * @param request
	 * @param map
	 */
	@RequestMapping(value="sendPmoDynamiSalesDataJob")
	public void sendPmoDynamiSalesDataJob(HttpServletRequest request, ModelMap map) {
		String reqProjectPmoCode = request.getParameter("projectPmoCode");
		String month = request.getParameter("month");
		if(StringUtils.isBlank(month)) {
			Date now = new Date();
			month = DateUtils.DateToString(now, DateStyle.YYYYMM);
		}
		ProjectDto projectDto = new ProjectDto();
		projectDto.setMerchantId(Long.valueOf(MerchantEnum.GREEN_TOWN.getNo()));
		ResponseList<Project> responseList = projectServiceFacade.findByDto(projectDto);
		if (responseList.isSuccess() && responseList != null && !responseList.getEntity().isEmpty()) {
			try{
				for (Project p : responseList.getEntity()) {
					ProjectPmoDto pmoDto = new ProjectPmoDto();
					pmoDto.setProjectId(p.getId());
					ResponseList<ProjectPmo> pmoList = projectPmoServiceFacade.findByDto(pmoDto);
					if (pmoList != null && !pmoList.getEntity().isEmpty()) {
						String projectPmoCode = pmoList.getEntity().get(0).getPmoProjectCode();
						if(StringUtils.isNotBlank(reqProjectPmoCode) &&  !reqProjectPmoCode.equals(projectPmoCode)) {
							continue;
						}
						if (StringUtils.isBlank(projectPmoCode))
							continue;

						Response<LevelDynamiSalesData> response = pmoDynamicDataServiceFacade.quereyLevelDynamiSalesData(projectPmoCode, month);
						//Response<LevelDynamiSalesData> response = projectServiceFacade.quereyLevelDynamiSalesData(projectPmoCode, month);
						if (!response.isSuccess()) {
							continue;
						}
						boolean pmoPushFlag = projectServiceFacade.checkPmoPush(projectPmoCode);
						if(!pmoPushFlag){
							continue;
						}
						LevelDynamiSalesData levelDynamiSalesData = response.getEntity();
						String json = JSON.toJSONString(levelDynamiSalesData);
						String clientKey = pmoConfig.getClientKey();
						String seq = pmoConfig.getSeq();
						String digest = MD5.md5(clientKey + seq + pmoConfig.getClientPwd()).toUpperCase();
						String url = pmoConfig.getRequest_url() + "/api/v1/pmo/project-dynamic-sale/" + projectPmoCode;
						ResponseBody responseBody = RequestUtil.buildRequest(json, url, clientKey, seq, digest);
						if (!responseBody.getCode().equals("000000")) {
							logger.error("PMO动态销售数据推送错误：" + responseBody.getDesc());
						}
						PmoLogDto pmoLogDto = new PmoLogDto();
						pmoLogDto.setMerchantId(Long.valueOf(1));
						pmoLogDto.setDirection("1");
						if (responseBody.getCode().equals(ResponseEnums.RESPONSEENUMS_000000.getCode())) {// 成功
							pmoLogDto.setStatus("1");
						} else {
							pmoLogDto.setStatus("2");
						}
						pmoLogDto.setRequestParams(json);
						pmoLogDto.setDelFlag("0");
						pmoLogDto.setInterfaceName("销售动态信息");
						pmoLogDto.setReturnResult(JSON.toJSONString(responseBody));
						pmoLogServiceFacade.save(pmoLogDto);
					}
				}
			}catch (Exception ex){
				logger.error("推送PMO销售数据异常:", ex);
			}
		}
	}

	/**
	 * 系统自动弃客手动Job
	 * @param request
	 * @param map
	 */
	@RequestMapping(value="autoGiveupCustomer")
	public void autoGiveupCustomer(HttpServletRequest request, HttpServletResponse response, ModelMap map) throws Exception{
		response.setContentType("text/html;charset=UTF-8");
		Response<CommonResDTO> resDto = new Response<CommonResDTO>();
		String projectId = request.getParameter("projectId");
		if(StringUtils.isBlank(projectId)){
			CommonResDTO commDto = new CommonResDTO();
			commDto.setResult(ResultEnum.FAILURE.getNo());
			commDto.setErrorMsg("缺少项目参数!!!");
			resDto.setEntity(commDto);
			//return resDto;
		}else{
			resDto = customerServiceFacade.customerAutoGiveup(Long.valueOf(projectId));
		}
		response.getWriter().write(JSONObject.toJSONString(resDto));
	}
}
